package com.wwdx.service.impl;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import com.wwdx.BaseCommons;
import com.wwdx.model.WwdxBookModel;
import com.wwdx.service.WechatPublishServiceI;
import com.wwdx.utils.ConstantHolder;
import com.wwdx.utils.QrCodeUtil;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpQrcodeService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrBuilder;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.List;

/**
 * @author liguoliang
 * @date 2018/1/15 11:17
 */
@Service
public class WechatPublishServiceImpl extends BaseCommons implements WechatPublishServiceI {

    @Override
    public void sendCard(WxMpUser wxMpUser,int cardCount,int bookCount,BaseWxService service) throws WxErrorException{
        List<WwdxBookModel> wwdxBookModels = wwdxBookService.selectModelList(WwdxBookModel.builder().ishost(1).status(0).type(0).build(), 1, 1);
        WwdxBookModel wwdxBookModel = wwdxBookModels.get(0);
        String card = "/data/wwdx/static/pullxin/haibao.jpg",  headimg = wxMpUser.getHeadImgUrl(),card2 ="/data/wwdx/static/pullxin/00.png",
                bookimg = "/data/wwdx/static/cover/"+wwdxBookModel.getBookimg(), date = new DateTime().toString("HH:mm"),
                content = wwdxBookModel.getContentsummary(), outPath = "/data/wwdx/static/pullxin/"+wxMpUser.getUnionId()+".jpg";
        this.generalImgFile(card, card2,headimg, bookimg, date, String.valueOf(cardCount), String.valueOf(bookCount), content, outPath);
        WxMediaUploadResult imageMedia = service.getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, new File(outPath));
        WxMpKefuMessage message = new WxMpKefuMessage();
        message.setMsgType(WxConsts.KefuMsgType.IMAGE);
        message.setToUser(wxMpUser.getOpenId());
        message.setMediaId(imageMedia.getMediaId());
        service.getKefuService().sendKefuMessage(message);
    }

    @Override
    public void sendCard(WxMpUser wxMpUser, BaseWxService service,Long bookid) throws WxErrorException {
        WwdxBookModel book = wwdxBookService.getByBookId(bookid);
        String card1 = "/data/wwdx/static/pullxin/wwdx.png",card2 = "/data/wwdx/static/pullxin/00.png",
        outPath = "/data/wwdx/static/pullxin/"+wxMpUser.getUnionId()+".png";
        String bookimg = book.getBookimg();
        String bookrecommend = book.getBookrecommend();
        String headImg = wxMpUser.getHeadImgUrl();
        this.generalImgFile(card1,card2,outPath,bookimg,bookrecommend,headImg);
        WxMediaUploadResult imageMedia = service.getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, new File(outPath));
        WxMpKefuMessage message = new WxMpKefuMessage();
        message.setMsgType(WxConsts.KefuMsgType.IMAGE);
        message.setToUser(wxMpUser.getOpenId());
        message.setMediaId(imageMedia.getMediaId());
        service.getKefuService().sendKefuMessage(message);
    }

    /**
     * 生成听书打卡图片
     * @param card 背景图
     * @param headimg 头像
     * @param bookimg 书籍图片
     * @param date 日期
     * @param cardCount 打卡次数
     * @param bookCount 书籍数
     * @param content 书籍介绍
     * @param outPath 输出路径
     */
    private void generalImgFile(String card, String card2,String headimg, String bookimg,String date,
                                String cardCount,String bookCount,String content,String outPath) {
        //主图片的路径
        BufferedImage buffImg = null;
        try {
            buffImg = ImageIO.read(new FileInputStream(card));
            Graphics g = buffImg.getGraphics();
            //头像
            BufferedImage headImg = ImageIO.read(new URL(headimg));
            BufferedImage bi2 = new BufferedImage(headImg.getWidth(), headImg.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
            Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, headImg.getWidth(), headImg.getHeight());
            Graphics2D g2 = bi2.createGraphics();
            g2.setClip(shape);
            g2.drawImage(headImg, 0, 0,null);
            g2.setBackground(Color.green);
            g2.dispose();
            g.drawImage(bi2, 312, 102, 100,100,null);

            //书籍图片
            Graphics graphics = buffImg.getGraphics();
            graphics.setFont(new Font("微软雅黑", Font.BOLD, 32));
            graphics.setColor(Color.RED);
            BufferedImage bookImg = ImageIO.read(new FileInputStream(bookimg));
            graphics.drawImage(bookImg, 260, 348,196, 256, null);

            //小图标
            Graphics graphics3 = buffImg.getGraphics();
            BufferedImage buffImg2 = ImageIO.read(new FileInputStream(card2));
            graphics3.drawImage(buffImg2, 400, 574, 58,30,null);

            //时间文字写入
            g.setColor(Color.decode("#427650"));
            g.setFont(new Font("微软雅黑", Font.PLAIN, 30));
            g.drawString(date, 320, 250);
            //打卡次数写入
            String word;
            String cardContent = "早起天     ";
            String bookContent = "听书本";
            g.setColor(Color.decode("#ff0404"));
            g.setFont(new Font("微软雅黑", Font.PLAIN, 32));
            switch (cardCount.length()){
                case 1:
                    word = cardContent.substring(0, 2) + "    " + cardContent.substring(2);
                    graphics.drawString(cardCount, 290, 300);
                    g.setColor(Color.GRAY);
                    g.drawString(word, 220, 300);
                    this.generalBookWords(g,graphics,bookCount,bookContent);
                    break;
                case 2:
                    word = cardContent.substring(0, 2) + "      " + cardContent.substring(2);
                    graphics.drawString(cardCount, 270, 300);
                    g.setColor(Color.GRAY);
                    g.drawString(word, 200, 300);
                    this.generalBookWords(g,graphics,bookCount,bookContent);
                    break;
                case 3:
                    word = cardContent.substring(0, 2) + "        " + cardContent.substring(2);
                    graphics.drawString(cardCount, 250, 300);
                    g.setColor(Color.GRAY);
                    g.drawString(word, 180, 300);
                    this.generalBookWords(g,graphics,bookCount,bookContent);
                    break;
                default:
                    break;
            }
            //摘要
            int digestWidth = 455;
            int digestHeight = 110;
            int fontsize = 26;
            BufferedImage bufferedImage = new BufferedImage(digestWidth, digestHeight, BufferedImage.TYPE_INT_RGB);
            //设置图片的背景色
            Graphics2D graphics1 = bufferedImage.createGraphics();
            graphics1.fillRect(0, 0, digestWidth, digestHeight);
            graphics1.setColor(Color.decode("#427650"));
            Font font = new Font("微软雅黑", Font.PLAIN, fontsize);
            graphics1.setFont(font);
            //失真处理
            graphics1.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            graphics1.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
            //书籍简介文字写入
            StrBuilder sb = new StrBuilder();
            //书籍文字字数不能超过3行

            int count = 0 ,ctnum = 2,a=0;
            for (int i = 0; i < content.length(); i++) {
                a++;
                sb.append(content.charAt(i));
                if (count == ctnum){
                    if (i >= 34 && i <49) {
                        graphics1.drawString(sb.toString(), a * fontsize, 26+34+34);
                        sb.setLength(0);
                    }
                }
                if (i >= 0 && i <17) {
                    graphics1.drawString(sb.toString(), i*fontsize, 28);
                    sb.setLength(0);
                    if (i==16){
                        a=-1;
                        count ++;
                    }
                }
                if (count == 1){
                    if (i >= 17 && i <34){
                        graphics1.drawString(sb.toString(), a*fontsize, 28+34);
                        sb.setLength(0);
                        if (i==33){
                            a=-1;
                            count ++;
                        }
                    }
                }
                if (i>48){
                    //计算字体宽度 设置省略号
                    int textWidth = 50;
                    int height = 26;
                    BufferedImage bufferedImage2 = new BufferedImage(textWidth, height, BufferedImage.TYPE_INT_RGB);
                    Graphics2D graphics5 = bufferedImage2.createGraphics();
                    graphics5.fillRect(0, 0, textWidth, height);
                    graphics5.setColor(Color.decode("#427650"));
                    Font font2 = new Font("微软雅黑", Font.PLAIN, fontsize);
                    graphics5.setFont(font2);
                    graphics5.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    graphics5.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
                    graphics5.drawString("...",0,24);
                    Graphics graphics7 = bufferedImage.getGraphics();
                    graphics7.drawImage(bufferedImage2, 395, 74, textWidth,height,null);
                    graphics5.dispose();
                    graphics7.dispose();
                }
            }
            g.drawImage(bufferedImage, 126, 678, 455,110,null);
            graphics.dispose();
            g.dispose();
            ImageIO.write(buffImg, "jpg", new File(outPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void generalBookWords(Graphics g,Graphics graphics,String bookCount,String bookContent){
        //书籍数写入
        String bookWord = "";
        switch (bookCount.length()){
            case 1:
                bookWord = bookContent.substring(0, 2) + "    " + bookContent.substring(2);
                break;
            case 2:
                bookWord = bookContent.substring(0, 2) + "      " + bookContent.substring(2);
                break;
            case 3:
                bookWord = bookContent.substring(0, 2) + "        " + bookContent.substring(2);
                break;
            default:
                break;
        }
        graphics.drawString(bookCount, 455, 300);
        g.setColor(Color.GRAY);
        g.drawString(bookWord, 385, 300);
    }
//    private void generalBookWords(Graphics g,String bookCount,String bookContent){
//        //书籍数写入
//        String bookWord = "";
//        switch (bookCount.length()){
//            case 1:
//                bookWord = bookContent.substring(0, 2) + "    " + bookContent.substring(2);
//                break;
//            case 2:
//                bookWord = bookContent.substring(0, 2) + "      " + bookContent.substring(2);
//                break;
//            case 3:
//                bookWord = bookContent.substring(0, 2) + "        " + bookContent.substring(2);
//                break;
//            default:
//                break;
//        }
//        g.setColor(Color.RED);
//        g.drawString(bookCount, 455, 300);
//        g.setColor(Color.GRAY);
//        g.drawString(bookWord, 385, 300);
//    }

    @Override
    public String getQrcodeUrl(String sources,BaseWxService service){
        String key = String.format(ConstantHolder.QRCODE_TICKET, sources);
        String ticket = (String) valueOperations.get(key);
        WxMpQrcodeService qrcodeService = service.getQrcodeService();
        try {
            if (StringUtils.isBlank(ticket)){
                WxMpQrCodeTicket wxMpQrCodeTicket = qrcodeService.qrCodeCreateTmpTicket(sources,24 * 60 * 60);
                ticket = wxMpQrCodeTicket.getTicket();
                valueOperations.set(key,ticket);
            }
            return service.shortUrl(qrcodeService.qrCodePictureUrl(ticket));
        }catch (WxErrorException e){
            logger.error("错误信息：{}",e.getMessage());
            return null;
        }
    }

    /**
     * 生成二维码
     */
    public void qrcode(WxMpUser wxMpUser,HttpServletResponse response)throws Exception {
        String openId = wxMpUser.getOpenId();
        String redirectURI = "merchant_url\\auth.html?merchantId=" + openId;
        QrCodeUtil.createImage(redirectURI,null,false);
    }
    //免费赠书
    private void generalImgFile(String card1,String card2, String outPath, String bookimg,String bookrecommend, String headimg){
        try {
            BufferedImage buffImg = ImageIO.read(new FileInputStream(card1));
            BufferedImage buffImg2 = ImageIO.read(new FileInputStream(card2));
            //头像
            Graphics graphics = buffImg.getGraphics();
            BufferedImage headImg2 = ImageIO.read(new URL(headimg));
            graphics.drawImage(headImg2, 42, 22, 86,86,null);

            //封面
            Graphics graphics2 = buffImg.getGraphics();
            BufferedImage bookimg2 = ImageIO.read(new URL(bookimg));
            graphics2.drawImage(bookimg2, 242, 411, 175,232,null);

            //小图标
            Graphics graphics3 = buffImg.getGraphics();
            graphics3.drawImage(buffImg2, 364, 614, 50,24,null);

            //摘要
            int digestWidth = 455;
            int digestHeight = 110;
            BufferedImage bufferedImage = new BufferedImage(digestWidth, digestHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics1 = bufferedImage.createGraphics();
            graphics1.setColor(Color.decode("#333"));
            Font font = new Font("微软雅黑", Font.PLAIN, 28);
            graphics1.setFont(font);
            //失真处理
            graphics1.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            graphics1.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
            // 计算文字长度，计算居中的x点坐标
            graphics1.drawString(bookrecommend, 0, 0);

            //整合摘要
            Graphics graphics4 = buffImg.getGraphics();
            graphics4.drawImage(bufferedImage, 94, 694, 455,110,null);

            graphics.dispose();
            graphics1.dispose();
            graphics2.dispose();
            graphics3.dispose();
            graphics4.dispose();
            ImageIO.write(buffImg, "png", new File(outPath));
        } catch (Exception e) {
            logger.error("错误信息：{}",e.getMessage());
        }
    }
}
//    private void generalImgFile(String card, String headimg, String bookimg,String date,
//                                String cardCount,String bookCount,String content,String outPath) {
//        //主图片的路径
//        try (InputStream is = new FileInputStream(card)){
//            //通过JPEG图象流创建JPEG数据流解码器
//            JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(is);
//            //解码当前JPEG数据流，返回BufferedImage对象
//            BufferedImage buffImg = jpegDecoder.decodeAsBufferedImage();
//            //得到画笔对象
//            Graphics g = buffImg.getGraphics();
//
//            //头像
//            BufferedImage headImg = ImageIO.read(new URL(headimg));
//            BufferedImage bi2 = new BufferedImage(headImg.getWidth(), headImg.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
//            Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, headImg.getWidth(), headImg.getHeight());
//            Graphics2D g2 = bi2.createGraphics();
//            g2.setClip(shape);
//            g2.drawImage(headImg, 0, 0,null);
//            g2.setBackground(Color.green);
//            g2.dispose();
//            g.drawImage(bi2, 300, 60, null);
//
//            //书籍图片
//            ImageIcon bookimgIcon = new ImageIcon(bookimg);
//            Image bookImg = bookimgIcon.getImage();
//            g.drawImage(bookImg, 260, 350,bookimgIcon.getIconWidth() / 3, bookimgIcon.getIconHeight() / 3, null);
//
//            //时间文字写入
//            g.setColor(Color.BLACK);
//            g.setFont(new Font("微软雅黑", Font.PLAIN, 35));
//            g.drawString(date, 320, 250);
//            //打卡次数写入
//            String word;
//            String cardContent = "早起天     ";
//            String bookContent = "听书本";
//            g.setColor(Color.RED);
//            g.setFont(new Font("微软雅黑", Font.PLAIN, 30));
//            switch (cardCount.length()){
//                case 1:
//                    word = cardContent.substring(0, 2) + "    " + cardContent.substring(2);
//                    g.drawString(cardCount, 290, 300);
//                    g.setColor(Color.GRAY);
//                    g.drawString(word, 220, 300);
//                    this.generalBookWords(g,bookCount,bookContent);
//                    break;
//                case 2:
//                    word = cardContent.substring(0, 2) + "      " + cardContent.substring(2);
//                    g.drawString(cardCount, 270, 300);
//                    g.setColor(Color.GRAY);
//                    g.drawString(word, 200, 300);
//                    this.generalBookWords(g,bookCount,bookContent);
//                    break;
//                case 3:
//                    word = cardContent.substring(0, 2) + "        " + cardContent.substring(2);
//                    g.drawString(cardCount, 250, 300);
//                    g.setColor(Color.GRAY);
//                    g.drawString(word, 180, 300);
//                    this.generalBookWords(g,bookCount,bookContent);
//                    break;
//                default:
//                    break;
//            }
//            //书籍简介文字写入
//            StrBuilder sb = new StrBuilder();
//            //书籍文字字数不能超过3行
//            int count = 0 ,ctnum = 3;
//            for (int i = 0; i < content.length(); i++) {
//                sb.append(content.charAt(i));
//                if (count == ctnum){
//                    break;
//                }
//                if (i > 0 && i % 15 == 0) {
//                    g.setColor(Color.black);
//                    g.setFont(new Font("微软雅黑", Font.PLAIN, 30));
//                    g.drawString(sb.toString(), 120, 650 + i * 2);
//                    sb.setLength(0);
//                    count ++;
//                }
//            }
//            if (count < ctnum){
//                if (sb.length() > 0){
//                    g.setColor(Color.BLACK);
//                    g.setFont(new Font("微软雅黑", Font.PLAIN, 30));
//                    g.drawString(sb.toString(), 120, 650 + 45 * 2);
//                    sb.setLength(0);
//                }
//            }
//            g.dispose();
//            ImageIO.write(buffImg, "jpg", new File(outPath));
//        }catch (IOException e){
//            logger.error("错误信息：{}",e.getMessage());
//        }
//    }